<template>
  <a-row class="j-select-biz-component-box" type="flex" :gutter="8">
    <a-col v-if="inputs" class="left" :class="{'full': !buttons}">
      <a-select
        :mode="multiple?'multiple':''"
        :showArrow="false"
        :placeholder="placeholder"
        v-model="selectValue"
        :options="selectOptions"
        allowClear
        :disabled="disabled"
        :open="selectOpen"
        style="width: 100%;"
        @dropdownVisibleChange="handleDropdownVisibleChange"
        @click.native="clickelSectButton"
      />
    </a-col>
    <a-col v-if="buttons" class="right">
      <a-button type="primary" :icon="searchIcon" :disabled="disabled" @click="clickelSectButton">
        {{ selectButtonText }}
      </a-button>
    </a-col>
    <j-select-biz-component-modal
      ref="component"
      :name="name"
      v-model="selectValue"
      :visible.sync="visible"
      v-if="visible"
      v-bind="modalProps"
      @options="handleOptions"
    />
  </a-row>
</template>

<script>
import JSelectBizComponentModal from './JSelectBizComponentModal'
import lodash from 'lodash'
import giftList from '@views/dms/promotion/giftList'

export default {
  name: 'JSelectBizComponent',
  components: { JSelectBizComponentModal },
  props: {
    name: {
      type: String,
    },
    checkVal: {
      type: Function | Object,
    },
    checkTip: {
      type: Function | Object,
    },
    value: {
      type: String,
      default: ''
    },
    /** 是否返回 id，默认 false，返回 code */
    returnId: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否支持多选，默认 true
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否显示按钮，默认 true
    buttons: {
      type: Boolean,
      default: true
    },
    // 是否显示输入框，默认 true
    inputs: {
      type: Boolean,
      default: true
    },
    // 显示的 Key
    displayKey: {
      type: String,
      default: null
    },
    searchIcon: {
      type: String,
      default: 'search'
    },
    // 返回的 key
    returnKeys: {
      type: Array,
      default: () => ['id', 'id']
    },
    giveBackList: {
      type: Array,
      default: () => []
    },
    // 选择按钮文字
    selectButtonText: {
      type: String,
      default: '选择'
    },
    returnName: {
      type: Boolean,
      default: false
    },
    dataSourceMap: {
      type: Object,
      default: {}
    },
    // 返回的 key
    rowKey: {
      type: String,
      default: 'id'
    },

  },
  data() {
    return {
      selectValue: [],
      selectOptions: [],
      visible: false,
      selectOpen: false,
    }
  },
  computed: {
    valueKey() {
      return this.returnId ? this.returnKeys[0] : this.returnKeys[1]
    },
    modalProps() {
      return Object.assign({
        rowKey: this.rowKey,
        valueKey: this.valueKey,
        multiple: this.multiple,
        returnKeys: this.returnKeys,
        displayKey: this.displayKey || this.valueKey,
        checkVal: typeof this.checkVal === 'function' ? this.checkVal() : this.checkVal,
        checkTip: this.checkTip,
      }, this.$attrs)
    },

  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        console.log(this.$attrs)
        if (val) {
          this.selectValue = val.split(',')
        } else {
          this.selectValue = []
        }
      }
    },
    // giveBackList:{
    //   deep:true,
    //   handler(val){
    //     val.forEach(item=>{
    //       this.dataSourceMap[item[this.returnKeys[1]]]=item
    //     })
    //     this.value = val.map(v=>v[this.returnKeys[1]])
    //   }
    // },
    selectValue: {
      deep: true,
      handler(val) {
        let rows = val.map(key => this.dataSourceMap[key])
        let data = ''
        try {
          if (this.returnName) {
            data = rows.map(item => item[this.displayKey]).join(',')
          } else {
            data = val.join(',')
          }
        } catch (err) {
          let list = []
          this.giveBackList.filter(item => {
            let index = val.findIndex(v => v == item[this.displayKey])
            if (index != -1) {
              list.push(item)
            }
          })
          rows = list
          data = val.join(',')
        }
        if (data !== this.value) {
          this.$emit('select', rows)
          this.$emit('input', data)
          this.$emit('change', data, this.dataSourceMap)
        }
      }
    }
  },
  methods: {
    handleOptions(options, dataSourceMap) {
      this.selectOptions = options
      this.dataSourceMap = dataSourceMap
    },
    handleDropdownVisibleChange() {
      // 解决antdv自己的bug —— open 设置为 false 了，点击后还是添加了 open 样式，导致点击事件失效
      this.selectOpen = true
      this.$nextTick(() => {
        this.selectOpen = false
      })
    },
    clickelSectButton() {
      if (this.disabled) {
        return
      }
      if (this.checkVal !== undefined) {
        let result = {}
        if (typeof this.checkVal === 'function') {
          result = this.checkVal()
        } else if (typeof this.checkVal === 'object') {
          result = this.checkVal
        }
        if (!lodash.isEmpty(result) && typeof result === 'object') {
          for (let key of Object.keys(result)) {
            if (key && (result[key] === undefined || result[key] === '')) {
              return this.$message.warn(this.checkTip[key])
            }
          }
        }
      }
      if (this.queryParams) {
        for (let key in queryParams) {
          this.$refs.component.queryParams[key] = this.queryParams[key]
        }
      }
      this.visible = true
      if (this.giveBackList.length > 0) {
        this.$nextTick(() => {
          this.$refs.component.selectedTable.dataSource = this.giveBackList
          this.$refs.component.selectedRowKeys = this.giveBackList.map(item => {
            return item[this.returnKeys[1]]
          })
          // this.$refs.component.rowKey = this.returnKeys[1]
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.j-select-biz-component-box {

  @width: 82px;

  .left {
    width: calc(100% - @width - 8px);

  }

  .right {
    width: @width;
  }

  .full {
    width: 100%;
  }

  /deep/ .ant-select-search__field {
    display: none !important;
  }
}
</style>
